<!DOCTYPE html>
<html>

<head>

    <meta charset="utf-8">
    <title>下载进度条</title>
    <script>
        function downloadFile() {
            const xhr = new XMLHttpRequest();
            const downloadUrl = '/file/text.txt';
            xhr.open('GET', downloadUrl, true);
            let i = 0;
            xhr.addEventListener('progress', function (event) {
                // 响应头要有 Content-Length
                if (event.lengthComputable) {
                    const percentComplete = event.loaded / event.total;
                    const percentText = `${percentComplete * 100}%`;
                    document.getElementById("progress").style.width = percentText;
                    document.getElementById("percent").innerText = percentText;
                    // element.animate()
                    console.log((++i) + ' - ' + percentComplete); // 最后输出1
                }
            }, false);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var blob = new Blob([xhr.response], { type: 'text/plain' });
                    var fileUrl = URL.createObjectURL(blob);
                    var link = document.createElement('a');
                    link.href = fileUrl;
                    link.download = '按需填就好了';
                    link.click();
                }
            };
            xhr.send();
        }
    </script>
</head>

<body>
    <div style="width: 600px; margin: 100px auto;">
        <p><a href="https://juejin.cn/post/6844903862009069575">戳这里看教程</a>。动画我不熟，就先这样了</p>
        <button onclick="downloadFile()">下载（不太完美，进度条跑完了才会真的下载文件到磁盘）</button>
        <br />
        <br />
        <div style="width: 500px; background-color: beige;">
            <div id="progress" style="width: 0%; background-color: blue; height: 20px;"></div>
        </div>
        <div id="percent">0%</div>
    </div>
</body>


</html>